var NodeReferenceAsmSelect = 
{
  settings:
  {
	filterPath : null
  },
  fn: {}
};

NodeReferenceAsmSelect.fn.termIdFiltersChange = function(id, fieldName)
{
	var selector = '#' + id + '-filters select.asmselect-filter';
	$(selector).change(function()
	{
		var filters = [];
		
		$(selector).each(function(index, element)
		{
			var val = $(this).attr('value');
			if (val)
			{
				filters.push('tid=' + val);
			}	
		});
		
		$.post(	NodeReferenceAsmSelect.settings.filterPath, 
				{'filters': filters.join(','), 'field_name' : fieldName}, 
				function(data)
				{
					NodeReferenceAsmSelect.fn.optionsChanged(id, data);
				});
	});
}

NodeReferenceAsmSelect.fn.optionsChanged = function(fieldName, options)
{
	var select = $('#edit-' + fieldName + '-nids');
	
	// save all selected options
	var selectedOptions = select.find("option[selected]");
	
	select.html(options).change();
	
	// add / reselect previously selected options
	for (var i = 0; i < selectedOptions.length; i++)
	{		
		var option = select.find("option[value='" + selectedOptions[i].value + "']");
		
		if (option.length)
		{
			// option exists, make sure it's selected
			option.attr('selected', 'selected');
		}
		else
		{
			select.append(selectedOptions[i]);
		} 
	}
	
	// reset all option ids 
	select.find("option").removeAttr('id');
	
	// trigger the change event to cause asmSelect to reprocess the options
	select.change();
}

